# -*- coding: utf-8 -*-

import mod.server.extraServerApi as serverApi

from enchantBase import EnchantBase

comp = serverApi.GetEngineCompFactory()
levelId = serverApi.GetLevelId()


class MoltenFire(EnchantBase):
    def __init__(self, system, playerId, enchantData, levels):
        EnchantBase.__init__(self, system, playerId, enchantData, levels)
        self.item_list = []
        self.item_list_before = []

    def isArmorEnchant(self):
        return False

    def onEnter(self):
        self.mSystem.ListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(), 'ServerPlayerTryDestroyBlockEvent', self, self.get_drop_around)
        self.mSystem.ListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(), 'DestroyBlockEvent', self, self.check_drop_around)
        pass

    def onExit(self):
        self.mSystem.UnListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(), 'ServerPlayerTryDestroyBlockEvent', self, self.get_drop_around)
        self.mSystem.UnListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(), 'DestroyBlockEvent', self, self.check_drop_around)
        pass

    def get_drop_around(self, args):
        comp_game = comp.CreateGame(levelId)
        self.item_list_before = comp_game.GetEntitiesAroundByType(args['playerId'], 8, 64)
        pass

    def check_drop_around(self, args):
        comp_game = comp.CreateGame(levelId)
        dim = args['dimensionId']
        self.item_list = comp_game.GetEntitiesAroundByType(args['playerId'], 8, 64)
        drop_items = []
        for i in self.item_list:
            if i not in self.item_list_before:
                drop_items.append(i)
        for i in drop_items:
            if self.melting(i, dim):
                comp_game.KillEntity(i)
        pass

    def melting(self, entity_id, dim):
        # type: (EnchantBase, str, int) -> bool
        """
        将一个物品实体变为其熔炼后产物。
        :param entity_id: 物品实体的实体id
        :param dim: 物品实体所在维度
        :return: 是否成功将物品变为熔炼后产物，如果物品没有熔炼产物，也会返回False。
        """
        comp_item = comp.CreateItem(levelId)
        comp_recipe = comp.CreateRecipe(levelId)
        comp_pos = comp.CreatePos(entity_id)
        comp_motion = comp.CreateActorMotion(entity_id)
        drop_dic = comp_item.GetDroppedItem(entity_id)
        drop_item = drop_dic['newItemName']
        melt_list = comp_recipe.GetRecipesByInput(drop_item, 'furnace', 0, 1)
        if len(melt_list) < 0:
            return False
        output = melt_list[0]['output']
        drop_dic['newItemName'] = output
        drop_dic['auxValue'] = 0
        item_pos = comp_pos.GetPos()
        item_motion = comp_motion.GetMotion()
        new_item_id = self.mSystem.CreateEngineItemEntity(drop_dic, dim, item_pos)
        comp_motion = comp.CreateActorMotion(new_item_id)
        comp_motion.SetMotion(item_motion)
        return True

